﻿using System;
using System.Text;
using System.Text.RegularExpressions;

namespace net.xBei.Helper {
    /// <summary>
    /// 
    /// </summary>
    public static partial class TextEncodingHelper {
        /// <summary>
        /// 注册额外的编码 Dotnet Core专用
        /// </summary>
        public static void RegisterProvider() {
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
        }

#if NET7_0_OR_GREATER
        /// <summary>
        /// Unicode转字符串
        /// </summary>
        /// <param name="source">经过Unicode编码的字符串</param>
        /// <returns>正常字符串</returns>
        public static string Unicode2String(this string source) {
            return UnicodeRegex().Replace(source,
                                          x => string.Empty + Convert.ToChar(Convert.ToUInt16(x.Result("$1"), 16)));
        }

        [GeneratedRegex("%u([0-9A-F]{4})", RegexOptions.IgnoreCase | RegexOptions.Compiled, "zh-CN")]
        private static partial Regex UnicodeRegex();
#else
        /// <summary>
        /// Unicode转字符串
        /// </summary>
        /// <param name="source">经过Unicode编码的字符串</param>
        /// <returns>正常字符串</returns>
        public static string Unicode2String(this string source) 
            => new Regex(@"%u([0-9A-F]{4})", RegexOptions.IgnoreCase | RegexOptions.Compiled)
                    .Replace(source, x => string.Empty + Convert.ToChar(Convert.ToUInt16(x.Result("$1"), 16)));
#endif
    }
}
